<template>
  <div class="hostgroup-management">
    <div class="card">
      <div class="card-header flex-between">
        <span>主机组列表</span>
        <button @click="showAddModal = true" class="btn">+ 添加主机组</button>
      </div>

      <div v-if="loading" class="text-center p-2">
        <div class="loading"></div>
      </div>

      <table v-else>
        <thead>
          <tr>
            <th>主机组名称</th>
            <th>描述</th>
            <th>主机数量</th>
            <th>创建时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="group in hostGroups" :key="group.id">
            <td>{{ group.name }}</td>
            <td>{{ group.description || '-' }}</td>
            <td>{{ group.host_count }}</td>
            <td>{{ formatDate(group.created_at) }}</td>
            <td>
              <div class="flex gap-1">
                <button @click="viewGroupHosts(group)" class="btn btn-info" style="padding: 4px 8px; font-size: 10px;" title="查看主机">主机</button>
                <button @click="editGroup(group)" class="btn" style="padding: 4px 8px; font-size: 10px;">编辑</button>
                <button @click="deleteGroup(group.id)" class="btn btn-danger" style="padding: 4px 8px; font-size: 10px;">删除</button>
              </div>
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <!-- 主机列表弹窗 -->
    <div v-if="showHostsModal" class="modal" @click.self="showHostsModal = false">
      <div class="modal-content modal-lg">
        <div class="modal-header">
          <h2>{{ currentGroup?.name }} - 主机列表</h2>
          <button @click="showHostsModal = false" class="modal-close">✕</button>
        </div>
        <div class="modal-body">
          <div v-if="groupHosts.length === 0" class="text-center p-2">
            该主机组暂无主机
          </div>
          <table v-else class="hosts-table">
            <thead>
              <tr>
                <th>主机名</th>
                <th>IP地址</th>
                <th>端口</th>
                <th>项目</th>
                <th>环境类型</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="host in groupHosts" :key="host.id">
                <td>{{ host.name }}</td>
                <td>{{ host.ip }}</td>
                <td>{{ host.port }}</td>
                <td>{{ host.project_name || '-' }}</td>
                <td>
                  <span v-if="getHostEnvType(host)" :class="['badge', getEnvBadgeClass(getHostEnvType(host))]">
                    {{ getHostEnvTypeName(host) }}
                  </span>
                  <span v-else>-</span>
                </td>
                <td>
                  <button 
                    @click="connectSSH(host)" 
                    class="btn btn-info btn-sm"
                    :disabled="!canConnectSSH"
                    :title="canConnectSSH ? 'SSH连接' : '需要超级管理员权限'">
                    🔌 SSH
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <!-- SSH连接终端区域 -->
    <div v-if="activeGroupTerminals.length > 0" class="group-ssh-container">
      <!-- 左侧主机索引 -->
      <div class="host-index-sidebar">
        <div class="sidebar-header">
          <h3>{{ currentGroup?.name }} - 主机</h3>
        </div>
        <div class="host-list">
          <div 
            v-for="host in groupHosts" 
            :key="host.id" 
            :class="['host-item', { 'active': isTerminalActive(host.id) }]"
            @click="switchToHost(host)">
            <div class="host-icon">🖥️</div>
            <div class="host-info">
              <div class="host-name">{{ host.name }}</div>
              <div class="host-ip">{{ host.ip }}</div>
            </div>
            <div v-if="isTerminalActive(host.id)" class="active-indicator">●</div>
          </div>
        </div>
      </div>

      <!-- 右侧终端显示区 -->
      <div class="terminals-display">
        <div v-for="term in activeGroupTerminals" :key="term.id" class="terminal-wrapper">
          <Terminal 
            v-show="term.id === activeTerminalId"
            :host-id="term.id" 
            :host-name="term.name"
            @close="closeGroupTerminal(term.id)"
          />
        </div>
      </div>
    </div>

    <!-- Add/Edit Modal -->
    <div v-if="showAddModal || showEditModal" class="modal" @click.self="closeModal">
      <div class="modal-content">
        <div class="modal-header">
          <h2>{{ showEditModal ? '编辑主机组' : '添加主机组' }}</h2>
          <button @click="closeModal" class="modal-close">✕</button>
        </div>
        <div class="modal-body">
          <form @submit.prevent="saveGroup">
            <div class="form-group">
              <label>主机组名称 *</label>
              <input v-model="formData.name" type="text" required />
            </div>
            <div class="form-group">
              <label>描述</label>
              <textarea v-model="formData.description" rows="4"></textarea>
            </div>
            <div class="form-group">
              <label>添加主机到该组</label>
              <select v-model="selectedHostIds" multiple size="8" class="host-selector">
                <option v-for="host in availableHosts" :key="host.id" :value="host.id">
                  {{ host.name }} - {{ host.ip }} ({{ host.environment_name || '无环境' }})
                </option>
              </select>
              <small class="text-muted">按住 Ctrl/Cmd 可以选择多个主机</small>
            </div>
            <div class="flex gap-1 mt-2">
              <button type="submit" class="btn">保存</button>
              <button type="button" @click="closeModal" class="btn btn-danger">取消</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import api from '../services/api'
import Terminal from '../components/Terminal.vue'
import message from '../utils/message'

const hostGroups = ref([])
const availableHosts = ref([])
const groupHosts = ref([])
const environments = ref([])
const loading = ref(false)
const showAddModal = ref(false)
const showEditModal = ref(false)
const showHostsModal = ref(false)
const currentGroup = ref(null)
const selectedHostIds = ref([])

// SSH连接相关
const activeGroupTerminals = ref([])
const activeTerminalId = ref(null)
const currentUser = ref(null)

const formData = ref({
  name: '',
  description: ''
})

// 检查是否有SSH连接权限
const canConnectSSH = computed(() => {
  return currentUser.value && currentUser.value.is_superuser
})

onMounted(() => {
  fetchHostGroups()
  fetchHosts()
  fetchEnvironments()
  fetchCurrentUser()
})

const fetchHostGroups = async () => {
  loading.value = true
  try {
    const response = await api.getHostGroups()
    hostGroups.value = response.results || response
  } catch (error) {
    console.error('Failed to fetch host groups:', error)
  } finally {
    loading.value = false
  }
}

const fetchHosts = async () => {
  try {
    const response = await api.getHosts()
    availableHosts.value = response.results || response
  } catch (error) {
    console.error('Failed to fetch hosts:', error)
  }
}

const fetchEnvironments = async () => {
  try {
    const response = await api.getEnvironments()
    environments.value = response.results || response
  } catch (error) {
    console.error('Failed to fetch environments:', error)
  }
}

const fetchCurrentUser = async () => {
  try {
    const response = await api.getCurrentUser()
    currentUser.value = response
  } catch (error) {
    console.error('Failed to fetch current user:', error)
  }
}

// 查看主机组的主机列表
const viewGroupHosts = async (group) => {
  currentGroup.value = group
  try {
    const response = await api.getHosts()
    const allHosts = response.results || response
    // 过滤出属于该主机组的主机
    groupHosts.value = allHosts.filter(host => host.host_group === group.id)
    showHostsModal.value = true
  } catch (error) {
    console.error('Failed to fetch hosts:', error)
    message.error('获取主机列表失败～\n' + (error.response?.data?.error || error.message))
  }
}

const editGroup = (group) => {
  formData.value = { ...group }
  // 获取该组的主机ID列表
  const groupId = group.id
  const hostsInGroup = availableHosts.value.filter(h => h.host_group === groupId)
  selectedHostIds.value = hostsInGroup.map(h => h.id)
  showEditModal.value = true
}

const saveGroup = async () => {
  try {
    let groupId
    
    // 先保存主机组
    if (showEditModal.value) {
      await api.updateHostGroup(formData.value.id, formData.value)
      groupId = formData.value.id
    } else {
      const response = await api.createHostGroup(formData.value)
      groupId = response.id
    }
    
    // 批量更新主机的host_group字段
    if (selectedHostIds.value.length > 0) {
      const updatePromises = selectedHostIds.value.map(hostId => {
        const host = availableHosts.value.find(h => h.id === hostId)
        if (host) {
          return api.updateHost(hostId, {
            ...host,
            host_group: groupId
          })
        }
        return Promise.resolve()
      })
      
      await Promise.all(updatePromises)
    }
    
    await fetchHostGroups()
    await fetchHosts()
    closeModal()
    message.success('主机组保存成功！✨')
  } catch (error) {
    console.error('Failed to save host group:', error)
    message.error('保存失败～\n' + (error.response?.data?.detail || error.message))
  }
}

const deleteGroup = async (id) => {
  const confirmed = await message.confirmDelete('这个主机组')
  if (!confirmed) return
  try {
    await api.deleteHostGroup(id)
    await fetchHostGroups()
    message.success('删除成功！✨')
  } catch (error) {
    console.error('Failed to delete host group:', error)
    message.error('删除失败～\n' + (error.response?.data?.detail || error.message))
  }
}

// SSH连接功能
const connectSSH = (host) => {
  if (!canConnectSSH.value) {
    message.warning('需要超级管理员权限才能使用SSH连接功能哦～')
    return
  }

  // 检查是否已经打开了该主机的终端
  const existingTerminal = activeGroupTerminals.value.find(t => t.id === host.id)
  if (existingTerminal) {
    activeTerminalId.value = host.id
    return
  }

  // 添加新的终端
  activeGroupTerminals.value.push({
    id: host.id,
    name: host.name
  })
  activeTerminalId.value = host.id
}

// 切换到指定主机
const switchToHost = (host) => {
  if (!isTerminalActive(host.id)) {
    connectSSH(host)
  } else {
    activeTerminalId.value = host.id
  }
}

// 检查终端是否已激活
const isTerminalActive = (hostId) => {
  return activeGroupTerminals.value.some(t => t.id === hostId)
}

// 关闭主机组终端
const closeGroupTerminal = (hostId) => {
  const index = activeGroupTerminals.value.findIndex(t => t.id === hostId)
  if (index > -1) {
    activeGroupTerminals.value.splice(index, 1)
    
    // 如果关闭的是当前激活的终端，切换到其他终端
    if (activeTerminalId.value === hostId) {
      if (activeGroupTerminals.value.length > 0) {
        activeTerminalId.value = activeGroupTerminals.value[0].id
      } else {
        activeTerminalId.value = null
      }
    }
  }
}

// 获取主机的环境类型
const getHostEnvType = (host) => {
  if (!host.environment) return null
  const env = environments.value.find(e => e.id === host.environment)
  return env ? env.env_type : null
}

// 获取环境类型名称
const getHostEnvTypeName = (host) => {
  const envType = getHostEnvType(host)
  if (!envType) return '-'
  
  const typeNames = {
    'dev': '开发环境',
    'test': '测试环境',
    'staging': '预发布环境',
    'prod': '生产环境'
  }
  return typeNames[envType] || envType
}

// 获取环境类型徽章样式
const getEnvBadgeClass = (envType) => {
  const classMap = {
    'dev': 'badge-online',
    'test': 'badge-unknown',
    'staging': 'badge-warning',
    'prod': 'badge-offline'
  }
  return classMap[envType] || 'badge-unknown'
}

const closeModal = () => {
  showAddModal.value = false
  showEditModal.value = false
  selectedHostIds.value = []
  formData.value = { name: '', description: '' }
}

const formatDate = (dateString) => {
  return new Date(dateString).toLocaleString('zh-CN')
}
</script>

<style scoped>
.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: linear-gradient(135deg, #ffffff 0%, #fff0f5 50%, #f0f8ff 100%);
  border: 3px solid;
  border-image: linear-gradient(135deg, #ff6b9d, #c471ed, #12c2e9) 1;
  border-radius: 20px;
  width: 90%;
  max-width: 600px;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 15px 50px rgba(255, 107, 157, 0.3);
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  border-bottom: 3px solid;
  border-image: linear-gradient(90deg, #ff6b9d, #c471ed, #12c2e9) 1;
  background: linear-gradient(135deg, rgba(255, 107, 157, 0.1), rgba(196, 113, 237, 0.1));
}

.modal-header h2 {
  color: #ff6b9d;
  text-transform: uppercase;
  letter-spacing: 2px;
  font-size: 20px;
  font-weight: 700;
  text-shadow: 0 2px 10px rgba(255, 107, 157, 0.3);
}

.modal-close {
  background: transparent;
  border: none;
  color: #ff6b9d;
  font-size: 28px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-weight: bold;
}

.modal-close:hover {
  transform: rotate(90deg) scale(1.2);
  color: #c471ed;
}

.modal-body {
  padding: 20px;
}

.modal-lg {
  max-width: 900px;
}

.btn-info {
  background: linear-gradient(135deg, #2196f3, #42a5f5);
  border-color: #2196f3;
}

.btn-info:hover {
  background: linear-gradient(135deg, #1976d2, #2196f3);
}

.host-selector {
  width: 100%;
  padding: 12px;
  background: rgba(255, 240, 245, 0.9);
  border: 2px solid #ffc0cb;
  border-radius: 12px;
  color: #333333;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.host-selector:focus {
  outline: none;
  border-color: #ff6b9d;
  box-shadow: 0 4px 20px rgba(255, 107, 157, 0.3);
}

.host-selector option {
  padding: 10px;
  background: #ffffff;
  color: #333333;
}

.host-selector option:checked {
  background: linear-gradient(135deg, #ff6b9d, #c471ed);
  color: #ffffff;
  font-weight: 700;
}

.hosts-table {
  width: 100%;
  margin-top: 10px;
}

.hosts-table th,
.hosts-table td {
  padding: 10px;
  text-align: left;
}

.text-muted {
  display: block;
  color: rgba(255, 107, 157, 0.6);
  font-size: 12px;
  margin-top: 6px;
  font-style: italic;
}

/* 对话框内的按钮样式 */
.modal-body .btn {
  background: linear-gradient(135deg, #ff6b9d, #c471ed);
  border: none;
  padding: 12px 28px;
  border-radius: 25px;
  color: #ffffff;
  font-weight: 700;
  font-size: 14px;
  cursor: pointer;
  transition: all 0.3s ease;
  box-shadow: 0 4px 15px rgba(255, 107, 157, 0.4);
  text-transform: uppercase;
  letter-spacing: 1px;
}

.modal-body .btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(255, 107, 157, 0.6);
  background: linear-gradient(135deg, #ff5a8d, #b361dd);
}

.modal-body .btn-danger {
  background: linear-gradient(135deg, #ff6b9d 0%, #ff8fab 100%);
  box-shadow: 0 4px 15px rgba(255, 107, 157, 0.3);
}

.modal-body .btn-danger:hover {
  background: linear-gradient(135deg, #ff5a8d 0%, #ff7a9b 100%);
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(255, 107, 157, 0.5);
}

/* 表单样式 - 确保在深色主题下可见 */
.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 10px;
  color: #ff6b9d;
  font-weight: 700;
  font-size: 15px;
  letter-spacing: 0.5px;
}

.form-group input[type="text"],
.form-group textarea {
  width: 100%;
  padding: 14px 16px;
  background: rgba(255, 240, 245, 0.8);
  border: 2px solid #ffc0cb;
  border-radius: 12px;
  color: #333333;
  font-size: 15px;
  font-family: inherit;
  transition: all 0.3s ease;
}

.form-group input[type="text"]:focus,
.form-group textarea:focus {
  outline: none;
  border: 2px solid #ff6b9d;
  background: #ffffff;
  box-shadow: 0 4px 20px rgba(255, 107, 157, 0.3);
  transform: translateY(-2px);
}

.form-group input[type="text"]::placeholder,
.form-group textarea::placeholder {
  color: rgba(255, 107, 157, 0.4);
}

.form-group textarea {
  resize: vertical;
  min-height: 100px;
}

/* SSH连接区域 */
.group-ssh-container {
  display: flex;
  margin-top: 20px;
  height: 600px;
  border: 2px solid var(--color-accent-cyan);
  border-radius: 8px;
  overflow: hidden;
}

/* 左侧主机索引栏 */
.host-index-sidebar {
  width: 250px;
  background: rgba(0, 0, 0, 0.3);
  border-right: 2px solid var(--color-accent-cyan);
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding: 15px;
  background: rgba(255, 70, 85, 0.1);
  border-bottom: 2px solid var(--color-accent-red);
}

.sidebar-header h3 {
  margin: 0;
  color: var(--color-accent-cyan);
  font-size: 14px;
  text-transform: uppercase;
  letter-spacing: 1px;
}

.host-list {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.host-item {
  display: flex;
  align-items: center;
  padding: 12px;
  margin-bottom: 8px;
  background: rgba(255, 255, 255, 0.05);
  border: 2px solid rgba(255, 70, 85, 0.2);
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s;
}

.host-item:hover {
  background: rgba(255, 70, 85, 0.1);
  border-color: var(--color-accent-red);
  transform: translateX(5px);
}

.host-item.active {
  background: rgba(0, 255, 200, 0.1);
  border-color: var(--color-accent-cyan);
}

.host-icon {
  font-size: 20px;
  margin-right: 10px;
}

.host-info {
  flex: 1;
}

.host-name {
  color: #fff;
  font-size: 13px;
  font-weight: 600;
  margin-bottom: 4px;
}

.host-ip {
  color: rgba(255, 255, 255, 0.6);
  font-size: 11px;
  font-family: monospace;
}

.active-indicator {
  color: var(--color-accent-cyan);
  font-size: 20px;
  animation: pulse 1.5s infinite;
}

@keyframes pulse {
  0%, 100% { opacity: 1; }
  50% { opacity: 0.3; }
}

/* 右侧终端显示区 */
.terminals-display {
  flex: 1;
  background: var(--color-bg-primary);
  overflow: hidden;
}

.terminal-wrapper {
  height: 100%;
}
</style>
